<?php

namespace App\Modules\Apicrzs\Http\Controllers\Wechat;

use App\Library\Pay\AliPayService;
use App\Modules\Apicrzs\Http\Controllers\BaseApicrzsController;
use App\Modules\Apicrzs\Services\Notify\JunDaNotifyServices;
use App\Modules\Apicrzs\Services\Notify\WxNotifyServices;
use App\Modules\Apicrzs\Services\WeChat\WechatPayService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use EasyWeChat\Pay\Application as payApp;
use EasyWeChat\Pay\Message;


use App\Modules\Admin\Entities\Member\UserCardModel;
use App\Modules\Apicrzs\Entities\UsersModel;
use App\Modules\Apicrzs\Entities\WaterCardTransactionModel;


use EasyWeChat\MiniApp\Application;
use Illuminate\Support\Facades\Log;


class PayNotifyControllers extends BaseApicrzsController
{
    // 处理 微信回调
    public function notifyRecharge(Request $request)
    {
        $wechat = new payApp(getWxConfig('MiniApp'));
        $server = $wechat->getServer();
        // 处理支付结果事件
//        $message = file_get_contents("php://input");
//        $WxNotify = new WxNotifyServices();
//        $WxNotify->callbackNotify(json_decode($message,true));
        $server->handlePaid(function (Message $message,\Closure $next) {
            $out_trade_no = $message['out_trade_no'];
            $transaction_id = $message['transaction_id'];
            $this->writeLog($message,$out_trade_no);
            $content='39- 微信支付订单号:'.$message['transaction_id'].',商户订单号:'.$message['out_trade_no'].',支付者:'.$message['payer']['openid'].'状态：'.$message['trade_state'];
            $this->writeLog($content,$out_trade_no);

            $WxNotify = new WxNotifyServices();
            $WxNotify->callbackNotify($message);
            Log::info($content);

        });
        // 默认返回 ['code' => 'SUCCESS', 'message' => '成功']
        return $server->serve();
    }

    public function notifyAlipay(Request $request)
    {
        AliPayService::handleNotify();
    }

    /**
     *  退款回调 ；
     * @param Request $request
     */
    public function pay_refunds(Request $request)
    {
        $pay_service = new WechatPayService();
        $res_pay = $pay_service->pay_refunds($request->all());
        return $this->sendApiSuccess($res_pay);
    }


    public function getConfig(): array
    {
        $wechat = Config::get('wechat')['MiniApp'];
        return [
            'app_id' => $wechat['app_id'],
            'secret' => $wechat['secret'],
            'mch_id' => $wechat['pay']['mch_id'],
            // v2 API 秘钥
            'v2_secret_key' => $wechat['pay']['v2_key'],
            // v3 API 秘钥
            'secret_key' => $wechat['pay']['v3_key'],
            'certificate' => $wechat['pay']['cert_path'],
            'private_key' => $wechat['pay']['key_path'],
            'notify_url' => $wechat['pay']['notify_url'],
            'http' => [
                'throw' => true, // 状态码非 200、300 时是否抛出异常，默认为开启
                'timeout' => 5.0,
            ],
        ];
    }

    /**
     *  骏达请求接口
     * @param $request
     * @return void
     */
    public function getJundaCallback(Request $request)
    {
        $file_name= 'junda-'.date('m-d');
        $params =  $request->all();
        $this->writeLog('get-'.$request->isMethod('get'),$file_name);
        $this->writeLog('post-'.$request->isMethod('POST'),$file_name);
        xdebug($params,'骏达请求接口-回调','junda');
        $jundaService = new JunDaNotifyServices();
        $jundaService->callback($params);
        return ['code' => 'SUCCESS', 'message' => '成功'];
    }

    /**
     *  根据订单号查询 微信是否支付成功
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getNotifyRecharge(Request $request)
    {
        $service = new  WxNotifyServices();
        $param = $service->getOrderInfo($request->all());
        return $this->sendApiSuccess($param,$service->getError());
    }
    function writeLog($msg,$file_name)
    {
        // $file_name = date("m-d");
        /**
         * 第一部分路径
         */
        $dirPath = storage_path() . '/logs/pay';
        if ( !is_dir($dirPath) ) @mkdir($dirPath);
        $dirPath .= '/' . date('Yn');
        if ( !is_dir($dirPath) ) @mkdir($dirPath);
        $dirPath .= '/' . date('n');
        if ( !is_dir($dirPath) ) @mkdir($dirPath);
        /**
         * 第二部分
         */
        file_put_contents($dirPath . '/' . $file_name. '.txt', "\n\n" . date('Y-m-d H:i:s') . "\n", FILE_APPEND);
        file_put_contents($dirPath . '/' . $file_name . '.txt', json_encode($msg,JSON_UNESCAPED_UNICODE), FILE_APPEND);
    }


}
